

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="caoyusang">
  <meta name="keywords" content="">
  <title>Spring基础知识 - caoyusang的科研日常</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>caoyusang</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/7.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-01-05 10:52" pubdate>
        2021年1月5日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      115
       分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">Spring基础知识</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 个月前
                
              </p>
            
            <div class="markdown-body" id="post-body">
              <h1 id="Spring"><a href="#Spring" class="headerlink" title="Spring"></a>Spring</h1><h2 id="优势"><a href="#优势" class="headerlink" title="优势"></a>优势</h2><ul>
<li>开源免费</li>
<li>轻量级、非入侵式的框架</li>
<li><code>控制反转IOC + 面向切面编程AOP</code></li>
<li>支持事务处理以及框架整合</li>
</ul>
<p>总结：Spring就是一个<code>轻量级</code>的<code>控制反转</code>和<code>面向切面编程</code>的框架</p>
<h2 id="Spring七大模块"><a href="#Spring七大模块" class="headerlink" title="Spring七大模块"></a>Spring七大模块</h2><img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/spring%E4%B8%83%E5%A4%A7%E6%A8%A1%E5%9D%97.png" srcset="/img/loading.gif" class="">
<h3 id="核心容器（Spring-Core）"><a href="#核心容器（Spring-Core）" class="headerlink" title="核心容器（Spring Core）"></a><strong>核心容器（Spring Core）</strong></h3><p>　　核心容器提供Spring框架的基本功能。Spring以bean的方式组织和管理Java应用中的各个组件及其关系。Spring使用BeanFactory来产生和管理Bean，它是<code>工厂模式</code>的实现。BeanFactory使用控制反转(IOC)模式将应用的配置和依赖性规范与实际的应用程序代码分开。</p>
<h3 id="应用上下文（Spring-Context）"><a href="#应用上下文（Spring-Context）" class="headerlink" title="应用上下文（Spring Context）"></a><strong>应用上下文（Spring Context）</strong></h3><p>　　Spring上下文是一个配置文件，向Spring框架提供上下文信息。Spring上下文包括企业服务，如JNDI、EJB、电子邮件、国际化、校验和调度功能。</p>
<h3 id="Spring面向切面编程（Spring-AOP）"><a href="#Spring面向切面编程（Spring-AOP）" class="headerlink" title="Spring面向切面编程（Spring AOP）"></a><strong>Spring面向切面编程（Spring AOP）</strong></h3><p>　　通过配置管理特性，Spring AOP 模块直接将面向方面的编程功能集成到了 Spring框架中。所以，可以很容易地使 Spring框架管理的任何对象支持AOP。Spring AOP 模块为基于 Spring 的应用程序中的对象提供了事务管理服务。通过使用 Spring AOP，不用依赖 EJB 组件，就可以将声明性事务管理集成到应用程序中。</p>
<h3 id="JDBC和DAO模块（Spring-DAO）"><a href="#JDBC和DAO模块（Spring-DAO）" class="headerlink" title="JDBC和DAO模块（Spring DAO）"></a><strong>JDBC和DAO模块（Spring DAO）</strong></h3><p>　　JDBC、DAO的抽象层提供了有意义的异常层次结构，可用该结构来管理异常处理，和不同数据库供应商所抛出的错误信息。异常层次结构简化了错误处理，并且极大的降低了需要编写的代码数量，比如打开和关闭链接。</p>
<h3 id="对象实体映射（Spring-ORM）"><a href="#对象实体映射（Spring-ORM）" class="headerlink" title="对象实体映射（Spring ORM）"></a><strong>对象实体映射（Spring ORM）</strong></h3><p>　　Spring框架插入了若干个ORM框架，从而提供了ORM对象的关系工具，其中包括了Hibernate、JDO和 IBatis SQL Map等，所有这些都遵从Spring的通用事物和DAO异常层次结构。</p>
<h3 id="Web模块（Spring-Web）"><a href="#Web模块（Spring-Web）" class="headerlink" title="Web模块（Spring Web）"></a><strong>Web模块（Spring Web）</strong></h3><p>　　Web上下文模块建立在应用程序上下文模块之上，为基于web的应用程序提供了上下文。所以Spring框架支持与Struts集成，web模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。</p>
<h3 id="MVC模块（Spring-Web-MVC）"><a href="#MVC模块（Spring-Web-MVC）" class="headerlink" title="MVC模块（Spring Web MVC）"></a><strong>MVC模块（Spring Web MVC）</strong></h3><p>　　MVC框架是一个全功能的构建Web应用程序的MVC实现。通过策略接口，MVC框架变成为高度可配置的。MVC容纳了大量视图技术，其中包括JSP、POI等，模型来有JavaBean来构成，存放于m当中，而视图是一个街口，负责实现模型，控制器表示逻辑代码，由c的事情。Spring框架的功能可以用在任何J2EE服务器当中，大多数功能也适用于不受管理的环境。Spring的核心要点就是支持不绑定到特定J2EE服务的可重用业务和数据的访问的对象，毫无疑问这样的对象可以在不同的J2EE环境，独立应用程序和测试环境之间重用。</p>
<h2 id="IOC控制反转思想"><a href="#IOC控制反转思想" class="headerlink" title="IOC控制反转思想"></a>IOC控制反转思想</h2><h3 id="控制反转原型"><a href="#控制反转原型" class="headerlink" title="控制反转原型"></a>控制反转原型</h3><ul>
<li>以前，程序<code>主动</code>创建对象，<code>对象创建的控制权</code>在程序员手中</li>
<li>现在，程序不再具有主动性，变成了<code>被动</code>的接受对象</li>
</ul>
<p>这种思想从本质上解决了问题，获得依赖对象的方式反转了。程序员<code>不用再去管理对象的创建</code>，只需要提供用户接口和接口实现类，使用set方法进行注入，创建何种对象的选择权交给用户。</p>
<p>这样使得系统耦合度大大降低，程序员可以专注于业务。<br>从业务层理解：</p>
<img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/IOC%E6%80%9D%E6%83%B3%E4%B8%9A%E5%8A%A1%E5%B1%82%E7%90%86%E8%A7%A3.png" srcset="/img/loading.gif" class="">
<h3 id="IOC本质"><a href="#IOC本质" class="headerlink" title="IOC本质"></a>IOC本质</h3><p>控制反转是一种通过描述(XML或者注解)使得<code>第三方生产或获取特定对象</code>的方式，在Spring中实现控制反转的是<code>IOC容器</code>，其实现方式为<code>依赖注入</code>(Dependency Injection)。</p>
<h2 id="简单样例——HelloSpring"><a href="#简单样例——HelloSpring" class="headerlink" title="简单样例——HelloSpring"></a>简单样例——HelloSpring</h2><h3 id="Maven导入Spring依赖包"><a href="#Maven导入Spring依赖包" class="headerlink" title="Maven导入Spring依赖包"></a>Maven导入Spring依赖包</h3><p>主要导两个：</p>
<ul>
<li>spring-webmvc(导入这个后，maven会自动帮我们补全额外的依赖)</li>
<li>spring-jdbc</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-webmvc<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>5.3.3<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-comment">&lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-jdbc<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>5.3.3<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>
<h3 id="项目目录"><a href="#项目目录" class="headerlink" title="项目目录"></a>项目目录</h3><img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/HelloSpring.png" srcset="/img/loading.gif" class="">
<h3 id="实体类编写"><a href="#实体类编写" class="headerlink" title="实体类编写"></a>实体类编写</h3><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Hello</span> </span>&#123;
    <span class="hljs-keyword">private</span> String str;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getStr</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> str;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setStr</span><span class="hljs-params">(String str)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.str = str;
    &#125;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Hello&#123;&quot;</span> +
                <span class="hljs-string">&quot;str=&#x27;&quot;</span> + str + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;</code></pre>
<h3 id="XML文件配置"><a href="#XML文件配置" class="headerlink" title="XML文件配置"></a>XML文件配置</h3><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;</span>&gt;</span>

    <span class="hljs-comment">&lt;!--Spring默认使用无参构造器创建对象--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;str&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span></code></pre>
<h3 id="测试类编写"><a href="#测试类编写" class="headerlink" title="测试类编写"></a>测试类编写</h3><pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.pojo.Hello;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-comment">// 获取Spring的上下文对象</span>
        ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">&quot;applicationContext.xml&quot;</span>);
        Hello hello = (Hello) context.getBean(<span class="hljs-string">&quot;hello&quot;</span>);
        System.out.println(hello.toString());
    &#125;
&#125;</code></pre>
<h3 id="IOC创建对象的方式"><a href="#IOC创建对象的方式" class="headerlink" title="IOC创建对象的方式"></a>IOC创建对象的方式</h3><h4 id="默认使用无参构造创建对象"><a href="#默认使用无参构造创建对象" class="headerlink" title="默认使用无参构造创建对象"></a>默认使用无参构造创建对象</h4><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--Spring默认使用无参构造器创建对象--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;str&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<h4 id="使用有参构造创建对象"><a href="#使用有参构造创建对象" class="headerlink" title="使用有参构造创建对象"></a>使用有参构造创建对象</h4><ul>
<li>首先实体类需要一个有参构造方法</li>
</ul>
<pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Hello</span><span class="hljs-params">(String str)</span> </span>&#123;
    <span class="hljs-keyword">this</span>.str = str;
&#125;</code></pre>
<ul>
<li><p>在xml配置文件中可使用三种方式进行对象创建：属性名、构造器参数下标、属性类型</p>
<ul>
<li>属性名</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--方式1,通过属性名--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;str&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<ul>
<li>构造器参数下标</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--方式2,通过参数下标--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">index</span>=<span class="hljs-string">&quot;0&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<ul>
<li>属性类型</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--方式3,通过参数类型（不推荐使用）--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello3&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;java.lang.String&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
</li>
</ul>
<h2 id="Spring配置"><a href="#Spring配置" class="headerlink" title="Spring配置"></a>Spring配置</h2><h3 id="给Bean对象取别名"><a href="#给Bean对象取别名" class="headerlink" title="给Bean对象取别名"></a>给Bean对象取别名</h3><h4 id="name-推荐使用"><a href="#name-推荐使用" class="headerlink" title="name(推荐使用)"></a><code>name(推荐使用)</code></h4><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--在bean标签最后添加name配置，可同时添加多个别名，别名之间用空格、逗号或者分号隔开(且分隔符可以混用)--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello2&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;helloByIndex h1 h2 h3&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">index</span>=<span class="hljs-string">&quot;0&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<h4 id="lt-alias-gt-可用，但没必要"><a href="#lt-alias-gt-可用，但没必要" class="headerlink" title="&lt;alias&gt;(可用，但没必要)"></a><code>&lt;alias&gt;(可用，但没必要)</code></h4><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--给bean对象取别名--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">alias</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;hello1&quot;</span> <span class="hljs-attr">alias</span>=<span class="hljs-string">&quot;helloByAttr&quot;</span>/&gt;</span></code></pre>
<h3 id="import"><a href="#import" class="headerlink" title="import"></a>import</h3><p>一般用于团队开发使用，可以将多个配置文件导入合并为一个</p>
<p><code>applicationContext.xml</code></p>
<pre><code class="hljs xml">import resource=&quot;applicationContext2.xml&quot;
import resource=&quot;applicationContext3.xml&quot;
import resource=&quot;applicationContext4.xml&quot;</code></pre>
<h2 id="DI依赖注入"><a href="#DI依赖注入" class="headerlink" title="DI依赖注入"></a>DI依赖注入</h2><h3 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h3><p>Bean对象的创建依赖于容器</p>
<h3 id="注入"><a href="#注入" class="headerlink" title="注入"></a>注入</h3><p>Bean对象中的所有属性，由容器来注入</p>
<h3 id="构造器注入"><a href="#构造器注入" class="headerlink" title="构造器注入"></a>构造器注入</h3><p>前面已经提到，Spring默认通过无参构造器进行注入，当然在有有参构造方法的前提下也可以使用有参构造器进行注入。</p>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;str&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;Spring&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<h3 id="Set注入"><a href="#Set注入" class="headerlink" title="Set注入"></a>Set注入</h3><h4 id="实体类Address"><a href="#实体类Address" class="headerlink" title="实体类Address"></a>实体类Address</h4><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Address</span> </span>&#123;
    <span class="hljs-keyword">private</span> String address;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAddress</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> address;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAddress</span><span class="hljs-params">(String address)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.address = address;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Address&#123;&quot;</span> +
                <span class="hljs-string">&quot;address=&#x27;&quot;</span> + address + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;</code></pre>
<h4 id="实体类Student"><a href="#实体类Student" class="headerlink" title="实体类Student"></a>实体类Student</h4><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">import</span> java.util.*;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>&#123;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> Address address;
    <span class="hljs-keyword">private</span> String[] books;
    <span class="hljs-keyword">private</span> List&lt;String&gt; hobbies;
    <span class="hljs-keyword">private</span> Map&lt;String, String&gt; card;
    <span class="hljs-keyword">private</span> Set&lt;String&gt; games;
    <span class="hljs-keyword">private</span> String wife;
    <span class="hljs-keyword">private</span> Properties info;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.name = name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Address <span class="hljs-title">getAddress</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> address;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAddress</span><span class="hljs-params">(Address address)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.address = address;
    &#125;

    <span class="hljs-keyword">public</span> String[] getBooks() &#123;
        <span class="hljs-keyword">return</span> books;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setBooks</span><span class="hljs-params">(String[] books)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.books = books;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;String&gt; <span class="hljs-title">getHobbies</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> hobbies;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setHobbies</span><span class="hljs-params">(List&lt;String&gt; hobbies)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.hobbies = hobbies;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Map&lt;String, String&gt; <span class="hljs-title">getCard</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> card;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCard</span><span class="hljs-params">(Map&lt;String, String&gt; card)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.card = card;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Set&lt;String&gt; <span class="hljs-title">getGames</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> games;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setGames</span><span class="hljs-params">(Set&lt;String&gt; games)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.games = games;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getWife</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> wife;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setWife</span><span class="hljs-params">(String wife)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.wife = wife;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Properties <span class="hljs-title">getInfo</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> info;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setInfo</span><span class="hljs-params">(Properties info)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.info = info;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Student&#123;&quot;</span> +
                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;address=&quot;</span> + address.getAddress() + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;books=&quot;</span> + Arrays.toString(books) + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;hobbies=&quot;</span> + hobbies + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;card=&quot;</span> + card + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;games=&quot;</span> + games + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;wife=&#x27;&quot;</span> + wife + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> + <span class="hljs-string">&#x27;\n&#x27;</span> +
                <span class="hljs-string">&quot;info=&quot;</span> + info +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;
</code></pre>
<h4 id="XML文件配置-1"><a href="#XML文件配置-1" class="headerlink" title="XML文件配置"></a>XML文件配置</h4><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;</span>&gt;</span>
    
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;address&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Address&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;addressByValue&quot;</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;address&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;JiangXi&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;student1&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Student&quot;</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;studentByValue&quot;</span>&gt;</span>
        <span class="hljs-comment">&lt;!--第一种：普通值注入value--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;name&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;caoyusang&quot;</span>/&gt;</span>
        <span class="hljs-comment">&lt;!--第二种：Bean注入, ref--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;address&quot;</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">&quot;addressByValue&quot;</span>/&gt;</span>
        <span class="hljs-comment">&lt;!--第三种：数组注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;books&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">array</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>《红楼梦》<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>《三国演义》<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>《水浒传》<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>《西游记》<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">array</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
        <span class="hljs-comment">&lt;!--List注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;hobbies&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">list</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>打篮球<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>lol<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>听歌<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">list</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
        <span class="hljs-comment">&lt;!--Map注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;card&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">map</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">entry</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;洛天依&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;老天爷&quot;</span>/&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">entry</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;鸡你太美&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;只因你太美&quot;</span>/&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">map</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
        <span class="hljs-comment">&lt;!--Set注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;games&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">set</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>LOL<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">value</span>&gt;</span>TFT<span class="hljs-tag">&lt;/<span class="hljs-name">value</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">set</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
<span class="hljs-comment">&lt;!--        &amp;lt;!&amp;ndash;empty注入&amp;ndash;&amp;gt;--&gt;</span>
<span class="hljs-comment">&lt;!--        &lt;property name=&quot;wife&quot; value=&quot;&quot;/&gt;--&gt;</span>
        <span class="hljs-comment">&lt;!--null注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;wife&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">null</span>/&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
        <span class="hljs-comment">&lt;!--Properties注入--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;info&quot;</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">props</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;学号&quot;</span>&gt;</span>20200829<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;性别&quot;</span>&gt;</span>男<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&quot;年龄&quot;</span>&gt;</span>23<span class="hljs-tag">&lt;/<span class="hljs-name">prop</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">props</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span></code></pre>
<h4 id="测试类"><a href="#测试类" class="headerlink" title="测试类"></a>测试类</h4><pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.pojo.Student;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-comment">// 获取Spring的上下文对象</span>
        ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">&quot;applicationContext.xml&quot;</span>);
        Student s = (Student) context.getBean(<span class="hljs-string">&quot;studentByValue&quot;</span>);
        System.out.println(s.toString());
    &#125;
&#125;</code></pre>
<h4 id="输出结果"><a href="#输出结果" class="headerlink" title="输出结果"></a>输出结果</h4><p><img src="D:/NutCloud/我的坚果云/pics/set注入.png" srcset="/img/loading.gif"/></p>
<h3 id="扩展方式注入"><a href="#扩展方式注入" class="headerlink" title="扩展方式注入"></a>扩展方式注入</h3><p>可以使用p命名空间和c命名空间进行注入</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--p命名空间注入，可以直接注入属性的值，property--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello99&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span> <span class="hljs-attr">p:str</span>=<span class="hljs-string">&quot;spring&quot;</span>/&gt;</span>
<span class="hljs-comment">&lt;!--c命名空间注入，通过构造器注入，constructor-args--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;hello100&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Hello&quot;</span> <span class="hljs-attr">c:str</span>=<span class="hljs-string">&quot;spring&quot;</span>/&gt;</span></code></pre>
<h2 id="Bean作用域"><a href="#Bean作用域" class="headerlink" title="Bean作用域"></a>Bean作用域</h2><img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/Bean%E4%BD%9C%E7%94%A8%E5%9F%9F.png" srcset="/img/loading.gif" class="">
<h3 id="单例模式-singleton"><a href="#单例模式-singleton" class="headerlink" title="单例模式(singleton)"></a>单例模式(singleton)</h3><p>一个单例bean只有一个共享实例被管理，所有对具有一个或多个与该bean定义匹配的ID的bean的请求都会导致Spring容器返回一个特定的bean实例。</p>
<p>当定义一个bean并将其定义为一个单例时，Spring IoC容器会为该bean定义所定义的对象创建一个实例。</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- the following is equivalent, though redundant (singleton scope is the default) --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;accountService&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.something.DefaultAccountService&quot;</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">&quot;singleton&quot;</span>/&gt;</span></code></pre>
<p>这个单实例存储在这样的单例bean的缓存中，所有后续的请求和引用都会返回缓存的对象。</p>
<p>下图显示了单例作用域的工作方式</p>
<img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F.png" srcset="/img/loading.gif" class="">
<h3 id="原型模式-prototype"><a href="#原型模式-prototype" class="headerlink" title="原型模式(prototype)"></a>原型模式(prototype)</h3><p>bean部署的原型模式作用范围将导致每次对特定bean发出请求时都会创建一个新的bean实例。</p>
<p>每次通过容器getBean()时都会产生一个新的对象。</p>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;accountService&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.something.DefaultAccountService&quot;</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">&quot;prototype&quot;</span>/&gt;</span></code></pre>
<p>作用域使用规则：</p>
<ul>
<li>对所有有状态bean使用原型作用域</li>
<li>对无状态bean使用单例作用域。</li>
</ul>
<h3 id="Web开发中常用的四大模式"><a href="#Web开发中常用的四大模式" class="headerlink" title="Web开发中常用的四大模式"></a>Web开发中常用的四大模式</h3><p><code>后面再补</code></p>
<h2 id="Spring的三种装配模式"><a href="#Spring的三种装配模式" class="headerlink" title="Spring的三种装配模式"></a>Spring的三种装配模式</h2><h3 id="XML显示配置"><a href="#XML显示配置" class="headerlink" title="XML显示配置"></a>XML显示配置</h3><p><code>配置地狱</code></p>
<h3 id="隐式自动装配"><a href="#隐式自动装配" class="headerlink" title="隐式自动装配"></a>隐式自动装配</h3><p>Spring会在上下文中自动寻找，并自动给bean装配属性。</p>
<h4 id="ByName"><a href="#ByName" class="headerlink" title="ByName"></a>ByName</h4><p>需要保证所有Bean的id唯一，而且id需要和自动注入的属性的set方法名后的属性一致</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--byName--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;person&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Person&quot;</span> <span class="hljs-attr">autowire</span>=<span class="hljs-string">&quot;byName&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;name&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;wandehua&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<h4 id="ByType"><a href="#ByType" class="headerlink" title="ByType"></a>ByType</h4><p>需要保证需要保证所有Bean的class唯一，而且class需要和自动注入的属性类型一致</p>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--byType--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;person&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Person&quot;</span> <span class="hljs-attr">autowire</span>=<span class="hljs-string">&quot;byType&quot;</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;name&quot;</span> <span class="hljs-attr">value</span>=<span class="hljs-string">&quot;wandehua&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span></code></pre>
<h4 id="使用注解实现自动装配"><a href="#使用注解实现自动装配" class="headerlink" title="使用注解实现自动装配"></a>使用注解实现自动装配</h4><ul>
<li>导入context约束</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:context</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans</span></span>
<span class="hljs-tag"><span class="hljs-string">        https://www.springframework.org/schema/beans/spring-beans.xsd</span></span>
<span class="hljs-tag"><span class="hljs-string">        http://www.springframework.org/schema/context</span></span>
<span class="hljs-tag"><span class="hljs-string">        https://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span></code></pre>
<ul>
<li>在XML文件中添加注解支持@Autowired</li>
</ul>
<pre><code class="hljs xml"><span class="hljs-comment">&lt;!--添加注解注入支持--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">context:annotation-config</span>/&gt;</span></code></pre>
<ul>
<li>给实体类属性填上自动注入的注解</li>
</ul>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>&#123;
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> Dog dog;
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> Cat cat;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.name = name;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Dog <span class="hljs-title">getDog</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> dog;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDog</span><span class="hljs-params">(Dog dog)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.dog = dog;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> Cat <span class="hljs-title">getCat</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> cat;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCat</span><span class="hljs-params">(Cat cat)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.cat = cat;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Person&#123;&quot;</span> +
                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&quot;, dog=&quot;</span> + dog +
                <span class="hljs-string">&quot;, cat=&quot;</span> + cat +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;
</code></pre>
<p>ps:</p>
<ol>
<li>@Autowired可以在属性上使用，也可以在set方法上使用(<code>官方推荐</code>)</li>
<li>@Autowired默认是<code>byType</code>方式，如果有多个相同type的bean对象</li>
</ol>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;dog1&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Dog&quot;</span>/&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;dog2&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.pojo.Dog&quot;</span>/&gt;</span></code></pre>
<p>需要配合@Qualifier(value = “bean id”)精准定位</p>
<pre><code class="hljs java"><span class="hljs-meta">@Autowired</span>
<span class="hljs-meta">@Qualifier(value = &quot;dog1&quot;)</span>
<span class="hljs-keyword">private</span> Dog dog;</code></pre>
<ol>
<li>当然还可使用java的原生注解@Resource进行自动注入，@Resource会执行byName和byType，都找不到则需要指定name</li>
</ol>
<pre><code class="hljs java"><span class="hljs-keyword">import</span> javax.annotation.Resource
    ...
<span class="hljs-meta">@Resource(name = &quot;dog1&quot;)</span></code></pre>
<h3 id="Java-config实现配置"><a href="#Java-config实现配置" class="headerlink" title="Java-config实现配置"></a>Java-config实现配置</h3><p><code>完全替代XML文件</code>，这种完全使用配置类的方式在SpringBoot中随处可见。</p>
<h4 id="配置类"><a href="#配置类" class="headerlink" title="配置类"></a>配置类</h4><p>相当于xml文件</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.config;

<span class="hljs-keyword">import</span> com.youzikeji.pojo.User;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.ComponentScan;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;

<span class="hljs-meta">@Configuration</span>  <span class="hljs-comment">//代表这是一个配置类</span>
<span class="hljs-meta">@ComponentScan(&quot;com.youzikeji.pojo&quot;)</span>    <span class="hljs-comment">//扫描包</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JavaConfig</span> </span>&#123;
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> User();
    &#125;
&#125;</code></pre>
<h4 id="实体类"><a href="#实体类" class="headerlink" title="实体类"></a>实体类</h4><p>使用注解进行Bean的获取和属性的注入</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Value;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Component;

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;
    <span class="hljs-keyword">private</span> String name;

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">return</span> name;
    &#125;
    <span class="hljs-meta">@Value(&quot;caoyusang&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.name = name;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-keyword">public</span> String
    toString() &#123;
        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;User&#123;&quot;</span> +
                <span class="hljs-string">&quot;name=&#x27;&quot;</span> + name + <span class="hljs-string">&#x27;\&#x27;&#x27;</span> +
                <span class="hljs-string">&#x27;&#125;&#x27;</span>;
    &#125;
&#125;</code></pre>
<h4 id="测试类-1"><a href="#测试类-1" class="headerlink" title="测试类"></a>测试类</h4><p>如果完全使用配置类方式去进行容器配置，那么只能通过<code>AnnotationConfigApplicationContext</code>获取容器，通过配置<code>类的class对象</code>进行配置加载。</p>
<pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.config.JavaConfig;
<span class="hljs-keyword">import</span> com.youzikeji.pojo.User;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.AnnotationConfigApplicationContext;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        ApplicationContext context = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext(JavaConfig.class);
        User user = (User) context.getBean(<span class="hljs-string">&quot;getUser&quot;</span>);
        System.out.println(user.getName());
    &#125;
&#125;</code></pre>
<h2 id="Spring使用注解开发"><a href="#Spring使用注解开发" class="headerlink" title="Spring使用注解开发"></a>Spring使用注解开发</h2><h3 id="获得对注解的支持"><a href="#获得对注解的支持" class="headerlink" title="获得对注解的支持"></a>获得对注解的支持</h3><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:context</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/context&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans</span></span>
<span class="hljs-tag"><span class="hljs-string">        https://www.springframework.org/schema/beans/spring-beans.xsd</span></span>
<span class="hljs-tag"><span class="hljs-string">        http://www.springframework.org/schema/context</span></span>
<span class="hljs-tag"><span class="hljs-string">        https://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span>

    <span class="hljs-comment">&lt;!--添加要扫描的包，该包下所有注解都会生效--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">context:component-scan</span> <span class="hljs-attr">base-package</span>=<span class="hljs-string">&quot;com.youzikeji.pojo&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">context:annotation-config</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span></code></pre>
<h3 id="获得Bean、进行属性注入以及作用域设定"><a href="#获得Bean、进行属性注入以及作用域设定" class="headerlink" title="获得Bean、进行属性注入以及作用域设定"></a>获得Bean、进行属性注入以及作用域设定</h3><p><code>@Component</code>放在类上，说明这个类被Spring管理了。</p>
<p><code>@Value</code>放在属性或者set方法上(<code>推荐</code>)，进行属性值的注入</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.pojo;

<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Value;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Component;

<span class="hljs-comment">//组件，等价于&lt;bean&gt;</span>
<span class="hljs-meta">@Component</span>
<span class="hljs-meta">@Scope(&quot;singleton&quot;)</span> <span class="hljs-comment">//作用域</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;

    <span class="hljs-meta">@Value(&quot;caoyusang&quot;)</span> <span class="hljs-comment">//等价于&lt;property&gt;</span>
    <span class="hljs-keyword">public</span> String name;
&#125;</code></pre>
<h3 id="Component的衍生注解"><a href="#Component的衍生注解" class="headerlink" title="@Component的衍生注解"></a>@Component的衍生注解</h3><p>在实际的web开发中，<code>@Component</code>根据MVC三层架构可以有三类衍生注解：</p>
<ul>
<li>dao层 —— <code>@Repository</code></li>
<li>service层 —— <code>@Service</code></li>
<li>controller层 —— <code>@Controller</code></li>
</ul>
<p>它们都代表了组件的意思，起着和@Component同样的效果，只是@Component在不同层的”分身”</p>
<h2 id="设计模式——代理"><a href="#设计模式——代理" class="headerlink" title="设计模式——代理"></a>设计模式——代理</h2><h3 id="静态代理"><a href="#静态代理" class="headerlink" title="静态代理"></a>静态代理</h3><h4 id="角色分析"><a href="#角色分析" class="headerlink" title="角色分析"></a>角色分析</h4><ul>
<li>抽象角色——一般使用接口或抽象类解决</li>
<li>真实角色——被代理的角色</li>
<li>代理角色——代理真实角色，真实角色能做的、不能做的，代理角色都一并做了</li>
<li>客户——访问代理对象的人</li>
</ul>
<h4 id="案例分析"><a href="#案例分析" class="headerlink" title="案例分析"></a>案例分析</h4><h5 id="业务接口"><a href="#业务接口" class="headerlink" title="业务接口"></a>业务接口</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.rent;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Rent</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rent</span><span class="hljs-params">()</span></span>;
&#125;</code></pre>
<h5 id="真实角色类——房东"><a href="#真实角色类——房东" class="headerlink" title="真实角色类——房东"></a>真实角色类——房东</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.rent;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Landlord</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Rent</span></span>&#123;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rent</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;房东要出租房屋&quot;</span>);
    &#125;
&#125;</code></pre>
<h5 id="代理角色——中介"><a href="#代理角色——中介" class="headerlink" title="代理角色——中介"></a>代理角色——中介</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.rent;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Agent</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Rent</span></span>&#123;
    <span class="hljs-keyword">private</span> Landlord landlord;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Agent</span><span class="hljs-params">()</span> </span>&#123;
    &#125;

    <span class="hljs-comment">//有参构造指定了被代理的对象</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Agent</span><span class="hljs-params">(Landlord landlord)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.landlord = landlord;
    &#125;

    <span class="hljs-comment">//房屋中介能做房东能做的，还能帮房东做他做不了的一些附属业务</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rent</span><span class="hljs-params">()</span> </span>&#123;
        seeHouse();
        landlord.rent();
        sign();
        charge();
    &#125;
    <span class="hljs-comment">//看房</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">seeHouse</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;看房&quot;</span>);
    &#125;
    <span class="hljs-comment">//签合同</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sign</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;签合同&quot;</span>);
    &#125;
    <span class="hljs-comment">//收中介费</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">charge</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;收中介费&quot;</span>);
    &#125;
&#125;</code></pre>
<h5 id="测试类-2"><a href="#测试类-2" class="headerlink" title="测试类"></a>测试类</h5><pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.rent.Agent;
<span class="hljs-keyword">import</span> com.youzikeji.rent.Landlord;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        Landlord landlord = <span class="hljs-keyword">new</span> Landlord();
        Agent agent = <span class="hljs-keyword">new</span> Agent(landlord);
        agent.rent();
    &#125;
&#125;</code></pre>
<h4 id="代理的优势与缺点"><a href="#代理的优势与缺点" class="headerlink" title="代理的优势与缺点"></a>代理的优势与缺点</h4><h5 id="优势-1"><a href="#优势-1" class="headerlink" title="优势"></a>优势</h5><ul>
<li>使真实角色的操作更纯粹，不必关注公共的业务</li>
<li>公共业务被交给代理角色，实现了业务分工</li>
<li>公共业务发生扩展时，方便集中管理</li>
</ul>
<h5 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h5><ul>
<li>一个真实角色就会产生一个代理，增加了代码量，降低了开发效率</li>
</ul>
<h3 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h3><h5 id="基于接口的动态代理"><a href="#基于接口的动态代理" class="headerlink" title="基于接口的动态代理"></a>基于接口的动态代理</h5><p>JDK动态代理</p>
<p><code>Proxy类</code>：提供了创建动态代理类和实例的静态方法<code>Proxy.newProxyInstance</code></p>
<p>生成动态代理实例</p>
<p><code>InvocationHandler接口</code>：代理实例调用处理程序的接口</p>
<p><code>动态代理实例</code></p>
<p>业务接口</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.proxy;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserService</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span></span>;
&#125;</code></pre>
<p>接口实现类</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.proxy;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserServiceImp</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserService</span></span>&#123;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;得到用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;增加用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;删除用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;更新用户&quot;</span>);
    &#125;
&#125;</code></pre>
<p>动态代理实现类</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.proxy;

<span class="hljs-keyword">import</span> org.springframework.cglib.proxy.InvocationHandler;

<span class="hljs-keyword">import</span> java.lang.reflect.Method;
<span class="hljs-keyword">import</span> java.lang.reflect.Proxy;

<span class="hljs-comment">//自动生成代理类</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProxyInvocationHandler</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">InvocationHandler</span> </span>&#123;

    <span class="hljs-comment">//被代理的接口</span>
    <span class="hljs-keyword">private</span> Object target;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTarget</span><span class="hljs-params">(Object target)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.target = target;
    &#125;

    <span class="hljs-comment">//生成代理类</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getProxy</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> Proxy.newProxyInstance(<span class="hljs-keyword">this</span>.getClass().getClassLoader(), target.getClass().getInterfaces(), <span class="hljs-keyword">this</span>::invoke);
    &#125;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object o, Method method, Object[] objects)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;
        log(method.getName());
        Object result = method.invoke(target, objects);
        <span class="hljs-keyword">return</span> result;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">log</span><span class="hljs-params">(String msg)</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;执行了&quot;</span> + msg + <span class="hljs-string">&quot;方法&quot;</span>);
    &#125;
&#125;</code></pre>
<p>测试类</p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.proxy;


<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;

        <span class="hljs-comment">//真实角色</span>
        UserServiceImp imp = <span class="hljs-keyword">new</span> UserServiceImp();
        <span class="hljs-comment">//代理角色</span>
        ProxyInvocationHandler pih = <span class="hljs-keyword">new</span> ProxyInvocationHandler();

        <span class="hljs-comment">//设置要代理的接口</span>
        pih.setTarget(imp);

        <span class="hljs-comment">//动态设置代理类</span>
        UserService proxy = (UserService) pih.getProxy();

        proxy.addUser();
    &#125;
&#125;</code></pre>
<p>效果展示</p>
<img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86.png" srcset="/img/loading.gif" class="">
<ul>
<li>一个动态代理类代理一般是接口的实现类，一般就是对应的一类业务</li>
<li>一个动态代理类可以代理多个接口实现类，只要这些类实现了同一个接口</li>
</ul>
<h5 id="基于类的动态代理"><a href="#基于类的动态代理" class="headerlink" title="基于类的动态代理"></a>基于类的动态代理</h5><p>cglib</p>
<h2 id="面向切面编程AOP"><a href="#面向切面编程AOP" class="headerlink" title="面向切面编程AOP"></a>面向切面编程AOP</h2><h3 id="AOP是什么"><a href="#AOP是什么" class="headerlink" title="AOP是什么"></a>AOP是什么</h3><p>AOP —— 面向切面编程，通过<code>预编译方式</code>和<code>运行期动态代理</code>实现程序<code>功能的统一维护</code>的一种技术。</p>
<p>利用AOP可以对业务逻辑的各个部分进行隔离，从而使得业务逻辑各部分之间的<code>耦合度降低</code>，提高程序的可重用性，同时提高了开发效率。</p>
<img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/aop.png" srcset="/img/loading.gif" class="">
<h3 id="原生Spring-API接口实现AOP"><a href="#原生Spring-API接口实现AOP" class="headerlink" title="原生Spring API接口实现AOP"></a>原生Spring API接口实现AOP</h3><h4 id="Demo"><a href="#Demo" class="headerlink" title="Demo"></a>Demo</h4><h5 id="业务接口-1"><a href="#业务接口-1" class="headerlink" title="业务接口"></a>业务接口</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.service;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserService</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delUser</span><span class="hljs-params">()</span></span>;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span></span>;
&#125;</code></pre>
<h5 id="接口实现类"><a href="#接口实现类" class="headerlink" title="接口实现类"></a>接口实现类</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.service;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserServiceImp</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">UserService</span></span>&#123;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;得到用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;增加用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;删除用户&quot;</span>);
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateUser</span><span class="hljs-params">()</span> </span>&#123;
        System.out.println(<span class="hljs-string">&quot;更新用户&quot;</span>);
    &#125;
&#125;</code></pre>
<h5 id="API接口实现"><a href="#API接口实现" class="headerlink" title="API接口实现"></a>API接口实现</h5><p><code>MethodBeforeAdvice接口</code></p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.log;

<span class="hljs-keyword">import</span> org.springframework.aop.MethodBeforeAdvice;

<span class="hljs-keyword">import</span> java.lang.reflect.Method;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BeforeLog</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MethodBeforeAdvice</span> </span>&#123;
    <span class="hljs-comment">//method: 要执行的目标对象的方法</span>
    <span class="hljs-comment">//objects: 参数</span>
    <span class="hljs-comment">//o: 目标对象</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">before</span><span class="hljs-params">(Method method, Object[] objects, Object o)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;
        System.out.println(o.getClass().getName()+<span class="hljs-string">&quot;的&quot;</span>+method.getName()+<span class="hljs-string">&quot;方法被调用了&quot;</span>);
    &#125;
&#125;</code></pre>
<p><code>AfterReturningAdvice接口</code></p>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.log;

<span class="hljs-keyword">import</span> org.springframework.aop.AfterReturningAdvice;

<span class="hljs-keyword">import</span> java.lang.reflect.Method;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AfterLog</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">AfterReturningAdvice</span> </span>&#123;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">afterReturning</span><span class="hljs-params">(Object o, Method method, Object[] objects, Object o1)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;
        System.out.println(<span class="hljs-string">&quot;执行了&quot;</span>+method.getName()+<span class="hljs-string">&quot;, 返回结果为:&quot;</span> + o);
    &#125;
&#125;</code></pre>
<h5 id="注册Bean"><a href="#注册Bean" class="headerlink" title="注册Bean"></a>注册Bean</h5><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">beans</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xmlns:aop</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/aop&quot;</span></span>
<span class="hljs-tag">       <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://www.springframework.org/schema/beans</span></span>
<span class="hljs-tag"><span class="hljs-string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span>
<span class="hljs-tag"><span class="hljs-string">        http://www.springframework.org/schema/aop</span></span>
<span class="hljs-tag"><span class="hljs-string">        http://www.springframework.org/schema/aop/spring-aop.xsd&quot;</span>&gt;</span>

    <span class="hljs-comment">&lt;!--注册bean--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;userService&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.service.UserServiceImp&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;beforeLog&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.log.BeforeLog&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;afterLog&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.log.AfterLog&quot;</span>/&gt;</span>

    <span class="hljs-comment">&lt;!--配置aop--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">aop:config</span>&gt;</span>
        <span class="hljs-comment">&lt;!--切入点--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:pointcut</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;pointcut&quot;</span> <span class="hljs-attr">expression</span>=<span class="hljs-string">&quot;execution(* com.youzikeji.service.UserServiceImp.*(..))&quot;</span>/&gt;</span>

        <span class="hljs-comment">&lt;!--执行环绕增加--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:advisor</span> <span class="hljs-attr">advice-ref</span>=<span class="hljs-string">&quot;beforeLog&quot;</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">&quot;pointcut&quot;</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:advisor</span> <span class="hljs-attr">advice-ref</span>=<span class="hljs-string">&quot;afterLog&quot;</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">&quot;pointcut&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">aop:config</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">beans</span>&gt;</span></code></pre>
<h5 id="测试类-3"><a href="#测试类-3" class="headerlink" title="测试类"></a>测试类</h5><pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.service.UserService;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">&quot;applicationContext.xml&quot;</span>);
        <span class="hljs-comment">// 代理的是接口</span>
        UserService service = (UserService) context.getBean(<span class="hljs-string">&quot;userService&quot;</span>);
        service.addUser();
    &#125;
&#125;</code></pre>
<h5 id="结果展示"><a href="#结果展示" class="headerlink" title="结果展示"></a>结果展示</h5><img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/aop%E7%BB%93%E6%9E%9C.png" srcset="/img/loading.gif" class="">
<h3 id="自定义切面实现AOP"><a href="#自定义切面实现AOP" class="headerlink" title="自定义切面实现AOP"></a>自定义切面实现AOP</h3><h5 id="自定义切面类"><a href="#自定义切面类" class="headerlink" title="自定义切面类"></a>自定义切面类</h5><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.aspect;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SurroundLog</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">before</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;方法执行前&quot;</span>);
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">after</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;方法执行后&quot;</span>);
    &#125;
&#125;</code></pre>
<h5 id="注册bean"><a href="#注册bean" class="headerlink" title="注册bean"></a>注册bean</h5><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--自定义切面--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;surroundLog&quot;</span> <span class="hljs-attr">class</span>=<span class="hljs-string">&quot;com.youzikeji.aspect.SurroundLog&quot;</span>/&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">aop:config</span>&gt;</span>
    <span class="hljs-comment">&lt;!--自定义切面，ref——要引用的类--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">aop:aspect</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">&quot;surroundLog&quot;</span>&gt;</span>
        <span class="hljs-comment">&lt;!--切入点--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:pointcut</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;point&quot;</span> <span class="hljs-attr">expression</span>=<span class="hljs-string">&quot;execution(* com.youzikeji.service.UserServiceImp.*(..))&quot;</span>/&gt;</span>
        <span class="hljs-comment">&lt;!--通知--&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:before</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;before&quot;</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">&quot;point&quot;</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">aop:after</span> <span class="hljs-attr">method</span>=<span class="hljs-string">&quot;after&quot;</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">&quot;point&quot;</span>/&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">aop:aspect</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">aop:config</span>&gt;</span></code></pre>
<h5 id="测试类-4"><a href="#测试类-4" class="headerlink" title="测试类"></a>测试类</h5><pre><code class="hljs java"><span class="hljs-keyword">import</span> com.youzikeji.service.UserService;
<span class="hljs-keyword">import</span> org.springframework.context.ApplicationContext;
<span class="hljs-keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">&quot;applicationContext.xml&quot;</span>);
        <span class="hljs-comment">// 代理的是接口</span>
        UserService service = (UserService) context.getBean(<span class="hljs-string">&quot;userService&quot;</span>);
        service.addUser();
    &#125;
&#125;</code></pre>
<h5 id="结果"><a href="#结果" class="headerlink" title="结果"></a>结果</h5><img src="/2021/01/05/Spring%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/diy-aop-res.png" srcset="/img/loading.gif" class="">
<h3 id="注解实现AOP"><a href="#注解实现AOP" class="headerlink" title="注解实现AOP"></a>注解实现AOP</h3><h4 id="开启扫描包和注解支持"><a href="#开启扫描包和注解支持" class="headerlink" title="开启扫描包和注解支持"></a>开启扫描包和注解支持</h4><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--扫描包--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">context:component-scan</span> <span class="hljs-attr">base-package</span>=<span class="hljs-string">&quot;com.youzikeji&quot;</span>/&gt;</span>
<span class="hljs-comment">&lt;!--开启注解支持--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">aop:aspectj-autoproxy</span>/&gt;</span></code></pre>
<h4 id="切面类"><a href="#切面类" class="headerlink" title="切面类"></a>切面类</h4><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.youzikeji.annotation;

<span class="hljs-keyword">import</span> org.aspectj.lang.annotation.After;
<span class="hljs-keyword">import</span> org.aspectj.lang.annotation.Aspect;
<span class="hljs-keyword">import</span> org.aspectj.lang.annotation.Before;
<span class="hljs-keyword">import</span> org.springframework.stereotype.Component;

<span class="hljs-meta">@Component</span>
<span class="hljs-comment">//切面类标注</span>
<span class="hljs-meta">@Aspect</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">annotationPointCut</span> </span>&#123;
    <span class="hljs-meta">@Before(&quot;execution(* com.youzikeji.service.UserServiceImp.*(..))&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">before</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;执行前&quot;</span>);
    &#125;

    <span class="hljs-meta">@After(&quot;execution(* com.youzikeji.service.UserServiceImp.*(..))&quot;)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">after</span><span class="hljs-params">()</span></span>&#123;
        System.out.println(<span class="hljs-string">&quot;执行后&quot;</span>);
    &#125;
&#125;
</code></pre>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Java/">Java</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Spring/">Spring</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/01/15/Redis%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Redis基础知识</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/12/14/MyBatis%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/">
                        <span class="hidden-mobile">MyBatis基础知识</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Spring基础知识&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  











</body>
</html>
